 /*
 * UMLSynch - Simple RMI part
 * http://umlsynch.googlecode.com
 *
 * Copyright 2008-2010, Evgeny Alexeyev
 * Licensed under the EPL - v1.0
 * http://www.eclipse.org/legal/epl-v10.html
 *
 */

package com.googlecode.umlsynch.rpc.base;

import java.util.ArrayList;
import java.util.ListIterator;


public class TDispatcherManager implements IDispatcher {
	private ArrayList<IDispatcher> dispatchers = new ArrayList<IDispatcher>();
	private TDebug debug;

	public TDispatcherManager(IDebug dbg) {
		debug = new TDebug(dbg);
	}
	
	@Override
	public boolean match(String interfaceName) {
		// There is a wrapper for all interfaces
		// therefore it shouldn't accept any interface
		return false;
	}

	@Override
	public void register(IDispatcher disp) {
		dispatchers.add(disp);		
	}

	@Override
	public void process(TIOHandler handler) {

		String data = handler.readString();

		debug.Note("Recieved:" + data);
		
		ListIterator<IDispatcher> iter = dispatchers.listIterator();
		boolean findFlag = false;

		if (data != null) {
			while (iter.hasNext()) {
				IDispatcher disp = iter.next();
				if (disp.match(data)) {
					findFlag = true;
					disp.process(handler);
					break;
				}
			}
		}
		if (!findFlag){
			// TODO: write some data into the socket to 
			// 		 avoid pending of client, but may be it is enought to 
			//       close socket to unlock client
			debug.Error("There no match for interface:" + data);
		}
		handler.close();
	}

}
